import { Component, OnInit } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/startWith';
import 'rxjs/add/observable/merge';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/observable/fromEvent';
import { MdPaginator, MdSnackBar, MD_DIALOG_DATA } from "@angular/material";
import { ApiServiceService } from '../api.service'
import { MdDialog, MdDialogRef } from '@angular/material';
import { ConstantService } from "../service/constant.service";
@Component({
  selector: 'app-platform',
  templateUrl: './platform.component.html',
  styleUrls: ['./platform.component.css']
})
export class PlatformComponent implements OnInit {

  constructor(private apiService: ApiServiceService,
    public snackBar: MdSnackBar,
    public dialog: MdDialog) {
  }
  platformInfo: any = {};
  heartChecked: boolean = true;
  signChecked: boolean = true;
  designChecked: boolean = true;
  // reportChecked:boolean = true;
  ifEdit = false;

  statusArray = ['开机/运行正常', "关机/停止运行", "故障", "故障恢复", "播发中"]
  configs: any;
  ifAddNode= false;
  primary

  ngOnInit() {
    this.apiService.getplatForm()
      .subscribe(res => {
        if (res.success) {
          this.platformInfo = res.data;
          sessionStorage.id = res.data.EBDID;
          console.log(this.platformInfo)
        }
      });
  }

  changeState(code) {
    this.apiService.changeState(code).subscribe(res => {
      if(res.success) {
        this.openSnackBar("状态改变成功", "");
        this.platformInfo.stateCode = code
      }
    })
  }

  setHeart() {
    this.apiService.setHeart()
      .subscribe(res => {
        if (res.success) {
          this.openSnackBar("设置心跳成功。", "");
        } else {
          this.openSnackBar("设置心跳失败,请稍后再试。", "");
        }
      });
  }
  setSign() {
    this.apiService.setSign()
      .subscribe(res => {
        if (res.success) {
          this.openSnackBar("设置加密成功。", "");
        } else {
          this.openSnackBar("设置加密失败,请稍后再试。", "");
        }
      });
  }
  setDesign() {
    this.apiService.setDesign()
      .subscribe(res => {
        if (res.success) {
          this.openSnackBar("设置解密成功。", "");
        } else {
          this.openSnackBar("设置解密失败,请稍后再试。", "");
        }
      });
  }
  setReport() {
    this.apiService.setReport()
      .subscribe(res => {
        if (res.success) {
          this.openSnackBar("设置自动上报成功。", "");
        } else {
          this.openSnackBar("设置自动上报失败,请稍后再试。", "");
        }
      });
  }
  openSnackBar(message: string, action: string) {
    this.snackBar.open(message, action, {
      duration: 3000,
    });
  }
  editPlatform() {
    if (this.ifEdit) {
      let platformInfo = this.platformInfo
      let msg;
      if (platformInfo.EBRName.trim().length == 0) {
        msg='平台名称不能为空'
      }else if (platformInfo.Address.trim().length == 0) {
        msg='地址名称不能为空'
      }else if (platformInfo.PhoneNumber.trim().length == 0) {
        msg='电话不能为空'
      }else if (platformInfo.Contact.trim().length == 0) {
        msg='联系人不能为空'
      }else if (!/^[1][3,4,5,7,8][0-9]{9}$/.test(platformInfo.PhoneNumber.trim())) {
        msg='电话号码格式不正确'
      }else if (platformInfo.Latitude.trim().length == 0 || platformInfo.Longitube.trim().length == 0) {
        msg='经纬度不能为空'
      }else if (!/^(-?\d+)(\.\d+)?$/.test(platformInfo.Longitube.trim()) || !/^(-?\d+)(\.\d+)?$/.test(platformInfo.Latitude.trim())) {
        msg='经纬度格式不对'
      }else if (platformInfo.Longitube.trim().split('.')[1] && platformInfo.Longitube.trim().split('.')[1].length > 6) {
        msg='经度浮点数进度不能超过6位'
      }else if (platformInfo.Latitude.trim().split('.')[1] && platformInfo.Latitude.trim().split('.')[1].length > 6) {
        msg='纬度浮点数进度不能超过6位'
      }else if (platformInfo.URL.trim().length == 0) {
        msg='网络地址不能为空'
      }else {
        var strRegex = '^((https|http|ftp|rtsp|mms)?://)'
        + '?(([0-9a-z_!~*\'().&=+$%-]+: )?[0-9a-z_!~*\'().&=+$%-]+@)?' //ftp的user@
        + '(([0-9]{1,3}.){3}[0-9]{1,3}' // IP形式的URL- 199.194.52.184
        + '|' // 允许IP和DOMAIN（域名）
        + '([0-9a-z_!~*\'()-]+.)*' // 域名- www.
        + '([0-9a-z][0-9a-z-]{0,61})?[0-9a-z].' // 二级域名
        + '[a-z]{2,6})' // first level domain- .com or .museum
        + '(:[0-9]{1,4})?' // 端口- :80
        + '((/?)|' // a slash isn't required if there is no file name
        + '(/[0-9a-z_!~*\'().;?:@&=+$,%#-]+)+/?)$';
        var re=new RegExp(strRegex);
        if (!re.test(platformInfo.URL.trim())) {
          msg='网络地址格式不对'
        }
      }
      if (msg) {
        this.openSnackBar(msg, "");
        return
      }

      this.apiService.saveConfig(this.platformInfo).subscribe(
        res => {
          if (res.success) {
            this.ifEdit = !this.ifEdit;
            this.openSnackBar("保存成功。", "");

          } else {
            this.openSnackBar("保存失败。", "");
          }
        }
      )
    } else {
      this.ifEdit = !this.ifEdit;
    }

  }

  /**
   * 修改节点
   * @param item
   */
  saveNode(item) {
    item.edit=false
    this.apiService.updateAccessNode({_id: item._id, ip: item.ip})
      .subscribe(res => {
        if (res.success) {
          this.openSnackBar("修改成功", "");
        }
      })
  }

  /**
   * 启用/禁用节点
   * @param item
   * @param e
   */
  changeNodeEnabel(item, e) {
    console.log(e)
    this.apiService.updateAccessNode({_id: item._id, enabel: e.checked})
    .subscribe(res => {
      if (res.success) {
        let msg = '启用成功';
        if (!e.checked) {
          msg = '禁用成功';
        }
        this.openSnackBar(msg, "");
      }
    })
  }

  /**
   * 删除节点
   * @param item
   */
  deleteNode(item) {
    this.apiService.deleteAccessNode(item._id)
      .subscribe(res => {
        if (res.success) {
          this.platformInfo.accessNodes = this.platformInfo.accessNodes.filter(node => node._id != item._id)
          this.openSnackBar("删除成功", "");
        }
      })
  }

  /**
   * 添加节点
   * @param value
   */
  addNode(value) {
    console.log(value)
    this.apiService.addAccessNode(value)
    .subscribe(res => {
      if (res.success) {
        this.ifAddNode = false
        this.platformInfo.accessNodes = res.data.accessNodes
        this.openSnackBar("添加成功", "");
      }
    })

  }
}




